package com.leyou.utils.test;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Arrays;
import java.util.List;
import java.util.Map;


public class Jsontest {
    public static void main(String[] args) {
        //创建对象
        User user = new User("jack", 21);
        String json = JsonUtils.toString(user);
        System.out.println("json = " + json);

        //集合的序列化
        List<User> list = Arrays.asList(new User("Rose", 18), user);
        json = JsonUtils.toString(list);
        //[{"name":"Rose","age":18},{"name":"jack","age":21}]
        System.out.println("json = " + json);

        //反序列化
        String str = "{\"name\":\"Jack\",\"age\":21}";
        User jack = JsonUtils.toBean(str, User.class);
        System.out.println("jack = " + jack);

        //反序列化集合
        str = "[{\"name\":\"Rose\",\"age\":18},{\"name\":\"jack\",\"age\":21}]";
        List<User> users = JsonUtils.toList(str, User.class);
        System.out.println("users = " + users);

        //反序列化 嵌套版本
        str = "{\"heima64\":[{\"name\":\"Rose\",\"age\":18},{\"name\":\"jack\",\"age\":21}],\"heima64\":[{\"name\":\"Rose\",\"age\":18},{\"name\":\"jack\",\"age\":21}]}" ;

        Map<String, List<User>> map = JsonUtils.nativeRead(str, new TypeReference<Map<String, List<User>>>() {
        });
        System.out.println("map = " + map);
    }

        @Data
        @AllArgsConstructor
        @NoArgsConstructor
        static class User {
            String name;
            Integer age;
        }
    }